<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');

/**
 * TYPOlight webCMS
 * Copyright (C) 2005-2009 Leo Feyer
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program. If not, please visit the Free
 * Software Foundation website at http://www.gnu.org/licenses/.
 *
 * PHP version 5
 * @copyright  Leo Feyer 2005-2009
 * @author     Leo Feyer <leo@typolight.org>
 * @package    News
 * @license    LGPL
 * @filesource
 */


/**
 * Table tl_orders
 */
$GLOBALS['TL_DCA']['tl_orders'] = array
(

	// Config
	'config' => array
	(
		'dataContainer'               => 'Table',
		'ctable'                      => array('tl_order_detail'),
		'switchToEdit'                => true,
		'enableVersioning'            => true
	),

	// List
	'list' => array
	(
		'sorting' => array
		(
			'mode'                    => 1,
			'fields'                  => array('orderno'),
			'flag'                    => 1,
			'panelLayout'             => 'filter;search,limit'
		),
		'label' => array
		(
			'fields'                  => array('orderno'),
			'format'                  => '%s'
		),
		'global_operations' => array
		(
			'export_id' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_orders']['export_id'],
				'href'                => 'key=export_id',
				'class'               => 'header_css_export_id',
				'attributes'          => 'onclick="Backend.getScrollOffset();"'
			),
			'export_skuid' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_orders']['export_skuid'],
				'href'                => 'key=export_skuid',
				'class'               => 'header_css_export_skuid',
				'attributes'          => 'onclick="Backend.getScrollOffset();"'
			),
			'all' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['MSC']['all'],
				'href'                => 'act=select',
				'class'               => 'header_edit_all',
				'attributes'          => 'onclick="Backend.getScrollOffset();"'
			)
		),
		'operations' => array
		(
			'edit' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_orders']['edit'],
				'href'                => 'table=tl_order_detail',
				'icon'                => 'edit.gif'
			),
			'delete' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_orders']['delete'],
				'href'                => 'act=delete',
				'icon'                => 'delete.gif',
				'attributes'          => 'onclick="if (!confirm(\'' . $GLOBALS['TL_LANG']['MSC']['deleteConfirm'] . '\')) return false; Backend.getScrollOffset();"'
			),
			'show' => array
			(
				'label'               => &$GLOBALS['TL_LANG']['tl_orders']['show'],
				'href'                => 'act=show',
				'icon'                => 'show.gif'
			)
		)
	),

	// Palettes
	'palettes' => array
	(
		'default'                     => '{title_legend},orderno,id_member;{address_legend},id_address_delivery,id_address_invoice;{payment_lengend},payment;{fee_legend},total_paid,total_paid_real,total_catolog 	,total_shipping,total_wrapping;{status_lengend},odr_status'
	),

	// Fields
	'fields' => array
	(
		'orderno' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['orderno'],
			'exclude'                 => true,
			'search'                  => true,
			'inputType'               => 'text',
			'eval'                    => array('mandatory'=>true, 'maxlength'=>255)
		),
		'id_member' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['id_member'],
			'exclude'                 => true,
			'search'                  => true,
			'inputType'               => 'text',
			'eval'                    => array('mandatory'=>true, 'maxlength'=>255)
		),
		'id_address_delivery' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['id_address_delivery'],
			'exclude'                 => true,
			'search'                  => true,
			'inputType'               => 'text',
			'eval'                    => array('mandatory'=>true, 'maxlength'=>255)
		),
		'id_address_invoice' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['id_address_invoice'],
			'exclude'                 => true,
			'search'                  => true,
			'inputType'               => 'text',
			'eval'                    => array('mandatory'=>true, 'maxlength'=>255)
		),
		'payment' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['payment'],
			'exclude'                 => true,
			'search'                  => true,
			'inputType'               => 'text',
			'eval'                    => array('mandatory'=>true, 'maxlength'=>255)
		),
		'total_paid' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['total_paid'],
			'exclude'                 => true,
			'search'                  => true,
			'inputType'               => 'text',
			'eval'                    => array('rgxp'=>'digit', 'tl_class'=>'w50')
		),
		'total_paid_real' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['total_paid_real'],
			'exclude'                 => true,
			'inputType'               => 'text',
			'eval'                    => array('rgxp'=>'digit', 'tl_class'=>'w50')
		),
		'total_catolog' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['total_catolog'],
			'exclude'                 => true,
			'inputType'               => 'text',
			'eval'                    => array('rgxp'=>'digit', 'tl_class'=>'w50')
		),
		'total_shipping' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['total_shipping'],
			'exclude'                 => true,
			'inputType'               => 'text',
			'eval'                    => array('rgxp'=>'digit', 'tl_class'=>'w50')
		),
		'total_wrapping' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['total_catolog'],
			'exclude'                 => true,
			'inputType'               => 'text',
			'eval'                    => array('rgxp'=>'digit', 'tl_class'=>'w50')
		),
		'odr_status' => array
		(
			'label'                   => &$GLOBALS['TL_LANG']['tl_orders']['odr_status'],
			'exclude'                 => true,
			'inputType'               => 'select',
			'options_callback'        => array('tl_orders', 'getOrderStatus'),
			'save_callback' => array
			(
				array('tl_orders', 'changeStatus')
			),
			'eval'					  => array('submitOnChange'=>true)
		)
		
	)
);


/**
 * Class tl_orders
 *
 * Provide miscellaneous methods that are used by the data configuration array.
 * @copyright  Leo Feyer 2005-2009
 * @author     Leo Feyer <leo@typolight.org>
 * @package    Controller
 */
class tl_orders extends Backend
{

	/**
	 * Import the back end user object
	 */
	public function __construct()
	{
		parent::__construct();
		$this->import('BackendUser', 'User');
	}
	
	public function getOrderStatus($dc)
	{
		$arrStatus = array();
		
		$objOrderStatus = $this->Database->prepare("SELECT name, id_order_state 
									FROM tl_order_state_lang
									WHERE id_lang=?")
						->execute(1);
					
		if ($objOrderStatus->numRows < 1)
			return $arrStatus;
		
		$index = 0;
		while ($objOrderStatus->next())
		{
			if ($index == 4)
				break;
			
			$arrStatus[$objOrderStatus->id_order_state] = $objOrderStatus->name;
			
			$index++;
		}
		
		return $arrStatus;
	}
	
	public function changeStatus($varValue, DataContainer $dc)
	{
		if ($varValue)
		{
			if ($dc->Input->post('payment') != 'Paypal')
			{
				switch ($varValue)
				{
					case '3': // send email to user.
					case '4': // send email to admin
						$email = new Email();
						
						$email->subject = "Message from Daft - Shipping";
						$email->from = $GLOBALS['TL_CONFIG']['adminEmail'];
						$email->fromName = "Daftshopping.com";
						$replyTo = "34n@gmail.com" . '<34n@gmail.com>';
						
						$shopName = "Daft";
						$id_order = $dc->Input->post('id');
						$shopurl = $this->Environment->base;
						$shoplog = $this->Environment->base . 'images/logo_order.jpg';
						$footerImg = $this->Environment->base . 'images/footer_log.jpg';
						
						// Get the member info.
						$objMember = $this->Database->prepare("SELECT tl_member.*,china_province.province_en,china_city.city_en FROM tl_member 
																LEFT JOIN china_province ON china_province.id=tl_member.state
																LEFT JOIN china_city ON china_city.pid=china_province.id
																WHERE tl_member.id=?")
													->execute($dc->Input->post('id_member'));
						$firstname = $objMember->firstname;
						$lastname = $objMember->lastname;
						$invoice_firstname = $objMember->firstname;
						$invoice_lastname = $objMember->lastname;
						$invoice_address1 = $objMember->street;
						$invoice_address2 = "";
						$invoice_city = $objMember->city_en;
						$invoice_country = $objMember->country;
						$invoice_state = $objMember->province_en;
						$invoice_phone = $objMember->phone;
						$invoice_email = $objMember->email;
						$invoice_postal = $objMember->postal;
						
						$invoice_tbls = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td><strong>BILLED TO </strong><p>COD</p><br/><br/><strong>BILLING ADDRESS</strong><p>" . $invoice_firstname . ' ' . $invoice_lastname . "<br/>" . $invoice_address1 ." <br/>" . $invoice_city . " " . $invoice_state . " " . $invoice_postal . "</p></td></tr></table>";
						// Get delivery address.
						$objShipping = $this->Database->prepare("SELECT tl_address_book.*,china_province.province_en,china_city.city_en FROM tl_address_book 
																LEFT JOIN china_province ON china_province.id=tl_address_book.state
																LEFT JOIN china_city ON china_city.pid=china_province.id
																WHERE tl_address_book.id=?")
													->execute($dc->Input->post('id_address_delivery'));
						$delivery_firstname = $objShipping->firstname;
						$delivery_lastname = $objShipping->lastname;
						$delivery_address1 = $objShipping->street;
						$delivery_address2 = "";
						$delivery_city = $objShipping->city_en;
						$delivery_postal_code = $objShipping->postcode;
						$delivery_country = $objShipping->country;
						$delivery_state = $objShipping->province_en;
						$delivery_phone = $objShipping->telephone;
						
						$delivery_tbls = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
								<tr>
								<td>
									<strong>SHIPPING ADDRESS</strong>
									<p>" . $delivery_firstname . ' ' . $delivery_lastname . "<br/>
										" . $delivery_address1 . " <br/>
										" . $delivery_city . " " . $delivery_state . " " . $delivery_postal_code . "</p>
								</td>
								</tr>
							</table>";
			
						// Mail product html	
						$tbl_products_left .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td colspan=\"2\" height=\"15\"></td></tr><tr><td width=\"100\">SKU</td><td>Name</td></tr>";
						
						$objCatalogs = $this->Database->prepare("SELECT `tl_order_detail`.*, `product_catalog`.skuid
																FROM `tl_order_detail` 
																INNER JOIN `product_catalog` ON `tl_order_detail`.product_catalog_id=`product_catalog`.id
																WHERE `tl_order_detail`.`pid`=?")
														->execute($dc->Input->post('id'));
						
						if ($objCatalogs->numRows < 1)
							return;
						
						$arrCatalogs = array();
						$index = 0;
						while ($objCatalogs->next())
						{
							$arrCatalogs[$index]['skuid'] = $objCatalogs->skuid;
							$arrCatalogs[$index]['product'] = $objCatalogs->product_name;
							$arrSizeColor = explode("\n", $objCatalogs->product_attribute);
							$arrSize = explode(':', $arrSizeColor[1]);
							$arrColor = explode(':', $arrSizeColor[0]);
							$arrCatalogs[$index]['colour'] = $arrColor[1];
							$arrCatalogs[$index]['size'] = $arrSize[1];
							$arrCatalogs[$index]['quantity'] = $objCatalogs->product_quantity;
							$arrCatalogs[$index]['unit_price'] = $objCatalogs->product_price;
							$arrCatalogs[$index]['total_price'] = intval($objCatalogs->product_price) * intval($objCatalogs->product_quantity);
							
							$index++;
						}
						
						foreach ($arrCatalogs as $strCatalogInfo)
						{
							$tbl_products_left .= "<tr><td colspan=\"2\" height=\"15\"></td></tr>";
							$tbl_products_left .= "<tr><td>" . $strCatalogInfo['skuid'] . "</td><td><p>" . $strCatalogInfo['product'] . "</p><p>" . $strCatalogInfo['size'] . ' ' . $strCatalogInfo['colour'] . "</p></td></tr>";					
						
						}
						$tbl_products_left .= "<tr><td height=\"40\" colspan=\"2\"></td></tr></table>";
						
						$tbl_products_right = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td colspan=\"2\" height=\"14\"></td></tr><tr><td width=\"100\">QTN</td><td width=\"100\">PRICE</td><td class=\"text_r\">SUBTOTAL</td></tr><tr><td colspan=\"3\" height=\"15\"></td></tr>";
						
						$index = 0;
						foreach ($arrCatalogs as $strCatalogInfo)
						{
						
							$tbl_products_right .= "<tr><td>" . $strCatalogInfo['quantity'] . "</td><td>" . $strCatalogInfo['unit_price'] . "</td><td class=\"text_r\">" . $strCatalogInfo['total_price'] . "</td></tr><tr>";
							
							$index++;
							if ($index < count($arrCatalogs))
								$tbl_products_right .= "<td colspan=\"3\" height=\"40\"></td></tr>";
													
						}
						
						$tbl_products_right .= "</table>";
						
						$tbl_products_right .= "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"order_total_price\"><tr><td width=\"170\">SUBTOTAL:</td><td class=\"text_r\">" . $dc->Input->post('total_catolog') . "</td></tr><tr><td>GIFT WRAPPING:</td><td class=\"text_r\">RMB" . $dc->Input->post('total_wrapping') . "</td></tr><tr><td>SHIPPING STANDARD:</td><td class=\"text_r\">RMB" . $dc->Input->post('total_shipping') . "</td></tr><tr><td colspan=\"2\" height=\"20\"></td></tr><tr><td><strong>TOTAL:</strong></td><td class=\"text_r\"><strong>RMB" . $dc->Input->post('total_paid_real') . "</strong></td></tr></table>";
						
						$total_products = $dc->Input->post('total_catolog');
						$total_shipping = $dc->Input->post('total_shipping');
						$total_paid = $dc->Input->post('total_paid_real');
						$payment = $dc->Input->post('payment');
						
						ob_start();
						include(TL_ROOT . "/mails/" . $GLOBALS['TL_LANGUAGE'] . "/order_conf.php");
						$strBuffer = ob_get_contents();
						ob_end_clean();
						
						$email->html = $strBuffer;
						if ($varValue == '3')
							$email->sendTo($invoice_email);
						else
							$email->sendTo($GLOBALS['TL_CONFIG']['adminEmail']);
						break;
					default:
						break;
				}
			}
		}
		
		$objOrderHistory = $this->Database->prepare("UPDATE `tl_order_history` SET `id_order_state`=? WHERE `id_order`=?")
										->execute($dc->Input->post('odr_status'), $dc->Input->post('id'));
										
		return $dc->Input->post('odr_status');
	}
}

?>